#!/bin/bash

# 设置备份目录-192.168.1.126
BACKUP_DIR="/gitlab_backup"
CONFIG_BACKUP_DIR="$BACKUP_DIR/config"
DATA_BACKUP_DIR="$BACKUP_DIR/data"
GITLAB_BACKUP_SRC="/var/opt/gitlab/backups"

# 创建相关目录（如果不存在）
mkdir -p "$BACKUP_DIR" "$CONFIG_BACKUP_DIR" "$DATA_BACKUP_DIR"

# 设置日期格式
DATE=$(date +%Y%m%d_%H%M%S)

# 备份配置文件
cp -a /etc/gitlab/gitlab.rb "$CONFIG_BACKUP_DIR/gitlab.rb.$DATE"
cp -a /etc/gitlab/gitlab-secrets.json "$CONFIG_BACKUP_DIR/gitlab-secrets.json.$DATE"


# 执行 GitLab 自带的备份命令
gitlab-backup create STRATEGY=copy


# 移动 GitLab 数据备份文件到指定目录
if ! find "$GITLAB_BACKUP_SRC" -name "*.tar" -exec mv {} "$DATA_BACKUP_DIR" \;; then
  echo "错误：未能移动备份文件，请检查源目录 $GITLAB_BACKUP_SRC 是否存在备份文件"
  exit 1
fi

# 只保留 10 个最新备份
echo "清理旧备份，只保留 10 个最新备份"
find "$BACKUP_DIR" -type f -name "*.*" | sort -r | tail -n +11 | xargs -I {} rm -f {}

# 输出备份完成信息
echo "GitLab 备份已完成，备份文件位于 $BACKUP_DIR"